package com.emagic.manage.common.preference;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;

import com.emagic.manage.biz.UserProfile;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.xitaiinfo.library.utils.EncryptUtils;
import com.xitaiinfo.library.utils.SimpleCrypto;

import java.util.ArrayList;

/**
 * 用户首选项信息
 *
 * @author baoy
 * @version 1.0
 *          Create by 16/4/26 下午5:49
 */
public class UserSharedPreference implements AppSharedPreference {

    public static final String PREFERENCE_NAME = "user";

    private static UserSharedPreference instance;

    private Context mContext;
    private SharedPreferences mSharedPreferences;
    private Gson gson;
    private static final String USER = "user";  //用户信息,AES加密保存

    public static UserSharedPreference getInstance(Context context) {
        if (instance == null) {
            instance = new UserSharedPreference(context);
        }
        return instance;
    }

    public UserSharedPreference(Context context) {
        this.mContext = context;
        this.mSharedPreferences = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
        this.gson = new Gson();
    }

    /**
     * 存储用户信息
     */
    public void putUserProfile(UserProfile userProfile) {
        mSharedPreferences.edit().putString(USER, encryptAES(userProfile)).apply();
    }


    /**
     * 获取存储的用户信息
     *
     * @return
     */
    public UserProfile getUserProfile() {
        String encryptedStr = mSharedPreferences.getString(USER, "");
        if (TextUtils.isEmpty(encryptedStr)) {
            return null;
        }
        String userJson = decryptAES(encryptedStr);

        if (!TextUtils.isEmpty(userJson)) {
            return gson.fromJson(userJson, UserProfile.class);
        }

        return null;

    }


    /*
        AES加密对象
     */
    private String encryptAES(Object obj) {
        String json = gson.toJson(obj, obj.getClass());
        //AES加密
        try {
            return SimpleCrypto.encrypt(EncryptUtils.generateAESPassword(), json);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /*
        AES解密
     */
    private String decryptAES(String str) {

        try {
            return SimpleCrypto.decrypt(EncryptUtils.generateAESPassword(), str);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    @Override
    public void clear() {

        mSharedPreferences.edit().clear().apply();
    }
}
